package nettools

import (
	"errors"
	"fmt"
	"net"
	"strings"

	"github.com/rs/zerolog/log"
)

func GetMacAddr(ipv4 string) (string, error) {

	ip := net.ParseIP(ipv4)
	if ip == nil {
		log.Error().Str("invalid-IP", ipv4)
		return "", errors.New("invalid ip")
	}

	currentIP := ipv4

	// get all the system's or local machine's network interfaces
	// only interested in the name with current IP address
	interfaces, _ := net.Interfaces()
	var currentNetworkHardwareName string
	for _, interf := range interfaces {
		if addrs, err := interf.Addrs(); err == nil {
			for _, addr := range addrs {

				if strings.Contains(addr.String(), currentIP) {
					currentNetworkHardwareName = interf.Name
				}
			}
		}
	}

	// extract the hardware information base on the interface name
	// capture above
	netInterface, err := net.InterfaceByName(currentNetworkHardwareName)

	if err != nil {
		fmt.Println(err)
		return "", err
	}

	return netInterface.HardwareAddr.String(), nil
}
